#define _CRT_SECURE_NO_WARNINGS
#include "DulList.h"

void DulListPrint(Node* phead) {
	assert(phead);
	Node* cur = phead->next;
	while (cur != phead) {
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

Node* DulListInit() {
	Node* phead = (Node*)malloc(sizeof(Node));
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

Node* DulListDestroy(Node* phead) {
	assert(phead);
	Node* cur = phead->next;
	while (cur != phead) {
		Node* next = cur->next;
		free(cur);
		cur = next;
	}
	free(phead);
}

Node* BuyListNode(TypeData x) {
	Node* newnode = (Node*)malloc(sizeof(Node));
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

void DulListPushBack(Node* phead, TypeData x) {
	assert(phead);
	Node* newnode = BuyListNode(x);
	Node* tail = phead->prev;
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;
}

void DulListPopBack(Node* phead) {
	assert(phead);
	assert(phead->next != phead);
	Node* tail = phead->prev;
	Node* pretail = tail->prev;
	pretail->next = phead;
	phead->prev = pretail;
	tail->prev = NULL;
	tail->next = NULL;
	free(tail);
}

void DulListPushFront(Node* phead, TypeData x) {
	assert(phead);
	Node* newnode = BuyListNode(x);
	Node* nextnode = phead->next;
	phead->next = newnode;
	newnode->next = nextnode;
	newnode->prev = phead;
	nextnode->prev = newnode;
}

void DulListPopFront(Node* phead) {
	assert(phead);
	assert(phead->next != phead);
	Node* popnode = phead->next;
	Node* nextnode = popnode->next;
	phead->next = nextnode;
	nextnode->prev = phead;
	free(popnode);
	popnode->next = NULL;
	popnode->prev = NULL;
}

Node* DulListFind(Node* phead, TypeData x) {
	Node* find = phead->next;
	while (find != phead) {
		if (find->data == x) {
			return find;
		}
		find = find->next;
	}
	return NULL;
}

void DulListInsert(Node* pos, TypeData x) {
	assert(pos);
	Node* pre = pos->prev;
	Node* newnode = BuyListNode(x);
	pre->next = newnode;
	newnode->next = pos;
	pos->prev = newnode;
	newnode->prev = pre;
}

void DulListErase(Node* pos) {
	assert(pos);
	Node* prenode = pos->prev;
	Node* nextnode = pos->next;
	prenode->next = nextnode;
	nextnode->prev = prenode;
	free(pos);
	pos = NULL;
}